package com.ma.controller;

import com.ma.common.dto.SysMenuDto;
import com.ma.common.dto.SysMenuVoDto;
import com.ma.common.lang.Result;
import com.ma.entity.SysMenu;
import com.ma.entity.SysUser;
import com.ma.service.SysMenuService;
import com.ma.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/*
        菜单控制器
        访问接口：/sys/menu/*
 */
@ResponseBody
@Controller
@Slf4j
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController{
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysUserService sysUserService;
    /*
        获取当前用户的菜单栏和权限信息
     */
    @GetMapping("/nav")
    //Principal 获取到用户的信息
    public Result nav(Principal principal){
        //获取当前登录的用户名字
        SysUser sysUser = sysUserService.getAllByUsername(principal.getName());
        //获取权限信息
        String authorityInfo = sysUserService.getUserAuthorityInfo(sysUser.getId());
        //因为存在逗号隔开 ，所以需要转换成数组的形式并去除逗号  ROLE_admin，ROLE_normal,sys:user:list
        String[] authorityInfotokenizeToStringArray = StringUtils.tokenizeToStringArray(authorityInfo, ",");

        //获取导航栏
        List<SysMenuDto> navs=sysMenuService.getCurrentUserNav();

        //用hasmap存储数据
        HashMap hashMap=new HashMap<>();
        hashMap.put("authoritys",authorityInfotokenizeToStringArray);
        hashMap.put("nav",navs);
        System.out.println(navs);

        return Result.succ(hashMap);
    }

    /*
        根据id查询菜单信息接口
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result info(@PathVariable(name = "id")int id){
        SysMenuVoDto sysMenuVoDto = sysMenuService.selectALLById(id);
        return Result.succ(sysMenuVoDto);
    }

    /*
        获取所有菜单信息接口
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result list(){
        List<SysMenuVoDto> sysMenuVoDtos=sysMenuService.getMenuTree();
        return Result.succ(sysMenuVoDtos);
    }
    /*
        获取保存菜单信息接口
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result save(@Validated @RequestBody SysMenu sysMenu) {
       sysMenu.setCreated(new Date());
       sysMenu.setStatu(1);
       sysMenuService.save(sysMenu);
        return Result.succ(sysMenu);
    }
    /*
       获取修改菜单信息接口
    */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result update(@Validated @RequestBody SysMenu sysMenu) {
        sysMenu.setUpdated(new Date());
        sysMenuService.update(sysMenu);
        //清除所有与该菜单相关的缓存
        sysUserService.clearUserAuthorityInfoByMenuId(sysMenu.getId());
        return Result.succ(sysMenu);
    }
    /*
       删除菜单信息接口
     */
    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result delete(@PathVariable(name = "id") Long id){
        //在删除前判断是否存在子集
        int count=sysMenuService.countByParentId(id);
        if (count >0){
            return Result.fail("请先删除子菜单");
        }
        sysMenuService.deleteBy(id);
        //同步删除中间关联表
        sysRoleMenuService.deleteByMenuId(id);
        //清除所有与该菜单相关的缓存
        sysUserService.clearUserAuthorityInfoByMenuId(id);

        return Result.succ("删除成功");
    }
}
